import { createApi } from '@halobear/request'

import { PROXY } from '@/constants'
import authority from './authority'

export default createApi({
  config: { baseURL: PROXY, shouldLoading: true, shouldToast: true },
  requestHandler(config) {
    const { token } = authority.get() || {}
    token && (config.headers.Authorization = `Bearer ${token}`)
    return config
  },
  errorHandler(e) {
    const { status } = (e || {}).response || {}
    if (status === 401) {
      authority.clear()
      setTimeout(() => {
        window.location.reload()
      }, 500)
    }
  },
})
